package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.Scanner;

public class Main extends JFrame {

    static Main main;
    PrintStream originalSTDOUT;

    Connection connection;
    String database;
    String table;

    public static void main(String[] args) throws IOException {
        try {
            main = new Main();
        } catch (IOException e) {
            PrintWriter printWriter = new PrintWriter("auth");
            printWriter.println("root");
            printWriter.println("A7btngqx");
            printWriter.close();
        } catch (Exception e) {
            if (!e.toString().contains("Column Index out of range"))
                JOptionPane.showMessageDialog(null, e.toString());
        }
    }

    private Main() throws SQLException, IOException {
        database = null;
        table = null;
        originalSTDOUT = System.out;

        Scanner scanner = new Scanner(new File("auth"));
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/sys",
                scanner.next(), scanner.next()
        );
        setTitle("MAIN");
        setSize(0x100, 0x100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        databaseSelect();
    }

    void databaseSelect() throws SQLException {
        Select databaseS = new Select(connection.prepareStatement("show databases"), "DATABASE");
        databaseS.confirm.addMouseListener(
                new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        try {
                            database = (databaseS.panel.group.getText());
                            if (database == null)
                                return;
                            database = removeSpaces(database);
                            System.out.println(database);
                            JOptionPane.showMessageDialog(null,
                                    String.format("database selected as %s", database)
                            );
                            connection.prepareStatement(
                                    String.format("use `%s`;", database)
                            ).execute();
                            tableSelect();
                        } catch (SQLException ex) {
                            System.out.println(ex);
                        }
                    }
                }
        );
    }

    void tableSelect() throws SQLException {
        Select tableS = new Select(connection.prepareStatement("show tables"), "TABLES");
        tableS.confirm.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    table = tableS.panel.group.getText();
                    if (table == null)
                        return;
                    table = removeSpaces(table);
                    JOptionPane.showMessageDialog(null,
                            String.format("database selected as %s", database)
                    );
                    new Select(connection.prepareStatement(
                            String.format("SELECT * FROM `%s`.`%s`;", database, table)
                    ),
                            "RESULT");
//                    ResultSet set=connection.prepareStatement(
//                            String.format("SELECT * FROM `%s`.`%s`;", database,table)
//                    ).executeQuery();
                } catch (SQLException exception) {
                    System.out.println(exception);
                }
            }
        });

    }

    private class Select extends JFrame {
        DataPanel panel;
        JButton confirm;

        private Select(PreparedStatement statement, String title) throws SQLException {
            this(statement, title, null);
        }

        private Select(PreparedStatement statement, String title, MouseListener listener) throws SQLException {
            setTitle(title);
            setLayout(new BorderLayout());
            setSize(0x100, 0x100);
            setDefaultCloseOperation(EXIT_ON_CLOSE);

            JLabel titleLabel = new JLabel(title);
            titleLabel.setFont(new Font("Monospace", Font.BOLD, 0x20));
            add(titleLabel, BorderLayout.NORTH);


            panel = new DataPanel(statement);
            add(panel, BorderLayout.CENTER);
            confirm = new JButton("Confirm");
            if (listener != null)
                confirm.addMouseListener(listener);
            add(confirm, BorderLayout.SOUTH);

            setVisible(true);

        }

        class DataPanel extends JPanel {
            ButtonTextGroup group;

            DataPanel(PreparedStatement statement) throws SQLException {

                setLayout(new GridBagLayout());

                GridBagConstraints constraint = new GridBagConstraints();
                constraint.gridx = 0;
                constraint.gridy = 0;

                group = new ButtonTextGroup();
                ResultSet set = statement.executeQuery();
                while (set.next()) {
                    while (true) {
                        try {
                            String baseName = set.getObject(constraint.gridx + 1).toString();
                            System.out.println("Got content--" + baseName);
                            JRadioButton button = new JRadioButton(
                                    String.format("%30s", baseName), false
                            );
                            constraint.gridx++;
                            if (constraint.gridx >= 0x10) {
                                constraint.gridy++;
                                constraint.gridx = 0;
                            }
                            add(button, constraint);
                            group.add(button);
                            button.setVisible(true);
                        } catch (Exception e) {
                            if (!e.toString().contains("Column Index out of range"))
                                JOptionPane.showMessageDialog(null, e.toString());
                            break;
                        }
                    }
                    constraint.gridx = 0;
                    constraint.gridy++;
                }
                setVisible(true);
            }
        }
    }

    static String removeSpaces(String s) {
        StringBuilder buffer = new StringBuilder();
        for (char i : s.toCharArray()) {
            if (!(i == ' '))
                buffer.append(i);
        }
        return buffer.toString();
    }
}

